package base;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;

class LibrarySystem {
	private List<Book> books = new ArrayList<>();
    private List<Reader> readers = new ArrayList<>();
    private List<BorrowRecord> records = new ArrayList<>();
    private final File recordFile = new File("borrow_records.txt");

    // 添加图书
    public void addBook(Book book) {
        books.add(book); // 不会报错 —保证 books 是 List 并已 import java.util.List/ArrayList
    }

    // 添加读者
    public void addReader(Reader reader) {
        readers.add(reader);
    }

    // 借书
    public void borrowBook(String readerId, String isbn) throws Exception {
        Reader reader = findReader(readerId);
        Book book = findBook(isbn);

        reader.borrowBook(book); // 可能抛出业务异常
        BorrowRecord record = new BorrowRecord(book, reader, LocalDate.now());
        records.add(record);
        saveRecordToFile(record);
        System.out.println("✅ 借书成功：" + record);
    }

    // 还书
    public void returnBook(String readerId, String isbn) throws Exception {
        Reader reader = findReader(readerId);
        Book book = findBook(isbn);

        BorrowRecord target = null;
        for (BorrowRecord r : records) {
            if (!r.isReturned()
                    && r.getBook().getIsbn().equals(book.getIsbn())
                    && r.getReader().getReaderId().equals(reader.getReaderId())) {
                target = r;
                break;
            }
        }

        if (target == null) {
            throw new NoSuchElementException("未找到对应的未归还借阅记录（读者：" + readerId + "，图书：" + isbn + "）");
        }

        reader.returnBook(book);
        target.setReturnDate(LocalDate.now());
        saveRecordToFile(target);
        System.out.println("✅ 还书成功：" + target);
    }

    // 查找图书
    private Book findBook(String isbn) throws NoSuchElementException {
        for (Book b : books) {
            if (b.getIsbn().equals(isbn)) return b;
        }
        throw new NoSuchElementException("未找到ISBN为 " + isbn + " 的图书！");
    }

    // 查找读者
    private Reader findReader(String readerId) throws NoSuchElementException {
        for (Reader r : readers) {
            if (r.getReaderId().equals(readerId)) return r;
        }
        throw new NoSuchElementException("未找到借书证号为 " + readerId + " 的读者！");
    }

    // 保存记录到文件（追加）
    private void saveRecordToFile(BorrowRecord record) {
        try (FileWriter fw = new FileWriter(recordFile, true);
             BufferedWriter bw = new BufferedWriter(fw)) {
            bw.write(record.toFileString());
            bw.newLine();
        } catch (IOException e) {
            System.out.println("⚠️ 保存记录失败：" + e.getMessage());
        }
    }

    public void showAllBooks() { books.forEach(System.out::println); }
    public void showAllRecords() { records.forEach(System.out::println); }
}
